// koa-multer
const multer = require('koa-multer');
const jimp = require('jimp');
const {AVATAR_PATH,PICTURE_PATH}=require('../const/filePath');
const path = require("path");
const avatarUpload = multer({ dest: './public/uploads/avatar' });
const pictureUpload = multer({ dest: './public/uploads/picture'})

const avatarHandler =avatarUpload.single('avatar');
const pictureHandler = pictureUpload.array('picture',9);
const pictureResize= async (ctx,next)=>{
  console.log('pictureResize中间件');
   let files = ctx.req.files;
   for(let file of files){
     const destPath = path.join(file.destination, file.filename);  //获取文件的绝对路径
     console.log(destPath);
     //压缩文件
     jimp.read(file.path, (err, image) => {
       if (err) throw err;
       //保存不同尺寸的图片
       image.resize(1280, jimp.AUTO).write(`${destPath}-large`);  //200x200
       image.resize(640, jimp.AUTO).write(`${destPath}-medium`); //100x100
       image.resize(320, jimp.AUTO).write(`${destPath}-small`); //50x50
     });
   }
    await next();
}


module.exports ={
  avatarHandler,
  pictureHandler,
  pictureResize

}